﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JXT.PrimaryKey.Batman.Collections
{
    /// <summary>
    /// 容器扩展类
    /// </summary>
    public static class CollectionExtensions
    {
        /// <summary>
        /// 无异常获取字典对象
        /// </summary>
        /// <typeparam name="TKey">key类型</typeparam>
        /// <typeparam name="TValue">value类型</typeparam>
        /// <param name="source">字典对象</param>
        /// <param name="key">字典key</param>
        /// <returns>获取的对象</returns>
        public static TValue SafeGet<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key)
        {
            return source.SafeGet(key, default(TValue));
        }

        /// <summary>
        /// 无异常获取字典对象
        /// </summary>
        /// <typeparam name="TKey">key类型</typeparam>
        /// <typeparam name="TValue">value类型</typeparam>
        /// <param name="source">字典对象</param>
        /// <param name="key">字典key</param>
        /// <param name="defaultValue">在对象不存在时，返回的默认对象</param>
        /// <returns>获取的对象</returns>
        public static TValue SafeGet<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue)
        {
            if (source == null)
                return defaultValue;
            TValue result;
            if (!source.TryGetValue(key, out result))
                result = defaultValue;
            return result;
        }
    }
}
